package fun.chutianshu.springsecurity_01.security;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fun.chutianshu.springsecurity_01.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;



import io.jsonwebtoken.ExpiredJwtException;

@Component
//自定义拦截器，在整个拦截器链前端
//用来拦截任意不能被匿名访问的接口
//验证访问请求中包含的 Token 是否合法
public class JwtRequestFilter extends OncePerRequestFilter {

    // 自定义的 jwt 用户信息类，用来验证用户名/密码
    @Autowired
    private JwtUserDetailsService jwtUserDetailsService;

    //自定义的 jwt 工具类，用来验证 token 签名
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    //复写了父类中拦截器逻辑
    @Override
    // 验证 token
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        // 把 请求中的验证字段 从 http header 的 Authorization 中读取出来
        final String requestTokenHeader = request.getHeader("Authorization");

        String username = null;
        String jwtToken = null;
        // JWT Token is in the form "Bearer token". Remove Bearer word and get
        // only the Token
        if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
            //读取 header 中的 jwt
            jwtToken = requestTokenHeader.substring(7);
            try {
                // 尝试从 token 中获取用户名
                username = jwtTokenUtil.getUsernameFromToken(jwtToken);
            } catch (IllegalArgumentException e) {
                System.out.println("Unable to get JWT Token");
            } catch (ExpiredJwtException e) {
                System.out.println("JWT Token has expired");
            }
        } else {
            logger.warn("JWT Token does not begin with Bearer String");
        }

        // Once we get the token validate it.
        // 验证 token 是否正确有效
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

            // 获取用户信息
            UserDetails userDetails = this.jwtUserDetailsService.loadUserByUsername(username);

            // if token is valid configure Spring Security to manually set
            // authentication
            // 直接调用 jwt 工具类来验证 token
            if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {
                // 把通过验证的 token 存入 服务器的安全上下文中
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                usernamePasswordAuthenticationToken
                        .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                // After setting the Authentication in the context, we specify
                // that the current user is authenticated. So it passes the
                // Spring Security Configurations successfully.
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
        }
        //正常过拦截器，向下一个拦截链发送
        chain.doFilter(request, response);
    }

}